﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Commander.Parsing;
using org.sablecc.grammars.java_1_5.node;

namespace Commander.Core.Refactorings.Modifiers {
	public class JLongParameterListModifier : JCodeModifier {

		private MethodInformation meth_info;

		public JLongParameterListModifier(MethodInformation info) {
			meth_info = info;
		}


		public StringBuilder NewClass { get; private set; }
		public override string ApplyModification() {
			if (meth_info.Parameters.Count > 0) {
				NewClass = new StringBuilder();
				string classname = GenId;
				string parameterName = GenId;
				NewClass.Append("class " + classname + "{ ");
				string text = meth_info.Body.ToString();
				//var parameters = (AManyFormalParameterList) meth_info.Parameters.FormalParameter;
				foreach (var item in meth_info.Parameters) {
					NewClass.Append("\npublic " + item.ToString()+";");
					text = ReplaceParam(item, text, parameterName);
				}
				NewClass.Append("\n} ");
				var p = new AReferenceFormalParameter();
				p.SetIdentifier1(new TIdentifier(classname));
				p.SetIdentifier2(new TIdentifier(parameterName));
				meth_info.Parameters.Add(p);
				var x = new ABlockMethodBody();;
				string[] fullText = meth_info.FullMethod.Split('\n');
				string pre = fullText[0].Substring(0, fullText[0].IndexOf('(') + 1);
				string declarator = pre + p.ToString() + ")";
				//meth_info.Body = 
				return declarator+text+"\n"+NewClass.ToString();
			}
			else {
				throw new NotImplementedException();
			}
		}

		private string ReplaceParam(PFormalParameter item, string text, string newParamName) {
			if (item is APrimitiveFormalParameter) {
				var parm = item as APrimitiveFormalParameter;
				var paramName = parm.GetIdentifier().ToString();
				string call = newParamName+"."+paramName;
				return text.Replace(paramName, call);
			}
			else {
				var parm = item as AReferenceFormalParameter;
				//var parm = item as APrimitiveFormalParameter;
				var paramName = parm.GetIdentifier2().ToString();
				string call = newParamName + "." + paramName;
				return text.Replace(paramName, call);
			}
		}
	}
}
